//
// Created by 11510 on 2024/7/8.
//

#ifndef REACTOR_ACCEPTOR_H
#define REACTOR_ACCEPTOR_H

#include "Socket.h"
#include "InetAddress.h"
#include <string>

class Acceptor {
private:
    Socket _sock;
    InetAddress _addr;

public:
    Acceptor(const std::string &ip, unsigned short port) :
            _sock(), _addr(ip, port) {}

    ~Acceptor() = default;

    void ready(){
        setReuseAddr();
        setReusePort();
        bind();
        listen();
    }

    int accept(){
        int connfd = ::accept(_sock.getFileDescriptor(), NULL, NULL);
        if(-1 == connfd){
            perror("accept");
            return -1;
        }
        return connfd;
    }

private:
    void setReuseAddr(){
        int on = 1;
        int ret = setsockopt(_sock.getFileDescriptor(), SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
        if (ret) {
            perror("setsockopt");
            return;
        }
    }

    void setReusePort(){
        int on = 1;
        int ret = setsockopt(_sock.getFileDescriptor(), SOL_SOCKET, SO_REUSEPORT, &on, sizeof(on));
        if (-1 == ret) {
            perror("setsockopt");
            return;
        }
    }

    void bind() {
        int ret = ::bind(_sock.getFileDescriptor(),
                         (struct sockaddr *) _addr.getInetAddressPtr(),
                         sizeof(struct sockaddr));
        if(-1 == ret){
            perror("bind");
            return;
        }
    }

    void listen(){
        /* 最大监听128个客户端 */
        int ret = ::listen(_sock.getFileDescriptor(), 128);
        if(-1 == ret){
            perror("listen");
            return;
        }
    }
};


#endif //REACTOR_ACCEPTOR_H
